package com.dong.common.util;

import com.dong.common.annotation.RequestMapping;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: 陈瑞东
 * @create: 2021-08-25 10:45
 */
public class Global {

    public static ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-content.xml");
    private static Map<String, Object[]> handlerMap = new HashMap<String, Object[]>();

    // 初始化controller映射
    static {
        // 获取所有的controller的bean名
        String[] beanNames = BeanFactoryUtils.beanNamesForAnnotationIncludingAncestors(context, Controller.class);
        for (String beanName : beanNames) {
            String classUrl = "";
            Object bean = context.getBean(beanName);
            // 获取类上的 RequestMapping 注解
            RequestMapping classAnnotation = bean.getClass().getAnnotation(RequestMapping.class);
            if (classAnnotation != null) {
                classUrl = classAnnotation.value();
                if (!classUrl.startsWith("/")) {
                    classUrl = "/" + classUrl;
                }
            }
            // 获取该类的方法
            Method[] methods = bean.getClass().getDeclaredMethods();
            for (Method method : methods) {
                String url = "";
                RequestMapping annotation = method.getAnnotation(RequestMapping.class);
                if (annotation != null) {
                    url = annotation.value();
                    if (!url.startsWith("/")) {
                        url = "/" + url;
                    }
                    handlerMap.put(classUrl + url, new Object[] {bean, method});
                }
            }
        }
    }

    /**
     * 获取controller映射的方法
     * @param path 路径
     * @return 方法独享
     */
    public static Object[] getController(String path) {
        return handlerMap.get(path);
    }



}
